package fr.u.psud.polytech.controller;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import fr.u.psud.polytech.database.Action;
import fr.u.psud.polytech.database.Entrepot;
import fr.u.psud.polytech.database.HibernateUtil;
import fr.u.psud.polytech.database.User;

public class ActionManager {
	public ActionManager(){
		super();
	}
	
	public List<Action> getAction(){
		List<Action> actionList= null;

		Transaction trns = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			Query query = session.createQuery("from Action");

			actionList= query.list();
			session.getTransaction().commit();
		} catch (RuntimeException ex) {
			if (trns != null) {
				trns.rollback();
			}
			ex.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}

		return actionList;
	}
	
	public Action getAction(Integer id) {
		Action a = null;

		Transaction trns = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			trns = session.beginTransaction();
			a = (Action) session.get(Action.class, id);
			session.getTransaction().commit();
		} catch (RuntimeException ex) {
			if (trns != null) {
				trns.rollback();
			}
			ex.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}

		return a;
	}
	
	public Action getAction(String url) {
		Action a= null;

		Transaction trns = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			trns = session.beginTransaction();
			Query query = session.createQuery("from Action where URL='"+url+"'");
			List<Action> actionList= query.list();
			if(!actionList.isEmpty()){
				a= actionList.get(0);
			}
			session.getTransaction().commit()	;
		} catch (RuntimeException ex) {
			if (trns != null) {
				trns.rollback();
			}
			ex.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		return a;
	}
}

